package cn.lili.modules.kit;

import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.SpringContextUtil;
import cn.lili.modules.payment.entity.dos.RefundLog;
import cn.lili.modules.payment.entity.dto.RefundParam;
import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
import cn.lili.modules.payment.service.PaymentSubsidiesService;
import cn.lili.modules.payment.service.RefundLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 退款支持
 *
 * @author Chopper
 * @since 2020-12-19 09:25
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class RefundSupport {

    private final RefundLogService refundLogService;
    /**
     * 售后退款
     *
     * @param refundParam 退款参数
     */
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public RefundLog refund(RefundParam refundParam) {
        RefundLog refundLog = RefundLog.builder()
                .userId(refundParam.getUserId())
                .orderSn(refundParam.getOrderSn())
                .afterSaleNo(refundParam.getSn())
                .payPrice(refundParam.getPayPrice())
                .paymentMethod(refundParam.getPaymentMethod())
                .outTradeNo(refundParam.getOutTradeNo())
                .transactionId(refundParam.getTransactionId())
                .isRefund(false)
                .price(refundParam.getPrice())
                .refundReason(refundParam.getRefundReason())
                .build();

        // 校验售后单是否处理过
        refundLogService.check(refundParam.getSn());

        PaymentMethodEnum paymentMethodEnum = PaymentMethodEnum.paymentNameOf(refundParam.getPaymentMethod());

        // 生成售后请求号
        refundLog.setOutRefundNo(SnowFlake.getIdStr());

        Payment payment = (Payment) SpringContextUtil.getBean(paymentMethodEnum.getPlugin());
        payment.refund(refundLog);

        refundLogService.save(refundLog);
        return refundLog;
    }


    /**
     * 退款通知
     *
     * @param paymentMethodEnum 支付渠道
     */
    public void notify(PaymentMethodEnum paymentMethodEnum) {

        //获取支付插件
        Payment payment = (Payment) SpringContextUtil.getBean(paymentMethodEnum.getPlugin());
        payment.refundNotify();
    }
}
